package com.zw.mes.module.system.service;

import com.zw.mes.entity.sys.User;
import com.zw.mes.module.system.mapper.DeptMapper;
import com.zw.mes.module.system.mapper.UserMapper;
import com.zw.mes.module.system.repository.UserRepository;
import com.zw.mes.util.ShiroUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

import static com.zw.mes.constant.Constant.STATUS_NORMAL;
import static com.zw.mes.util.BeanUtil.copy;

/**
 * @Description:
 *
 * @Author: China.sgl
 * @Date: 2019/9/16 09:11
 */
@Service
@SuppressWarnings("all")
public class UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private LogService logService;
    @Autowired
    private DeptMapper deptMapper;

    /**
     * 按条件查询用户
     *
     * @param user 查询条件
     * @return 用户表数据
     */
    public List<User> findUserByCondition(User user){
        return userMapper.findByCondition(user);
    }

    /**
     * 按帐号查询用户
     *
     * @param account 帐号
     * @return 用户数据
     */
    public User findUserByAccount(String account){
        return userMapper.findByAccount(account);
    }

    /**
     * 修改帐户
     *
     * @param user 帐户对象
     * @return 影响行数
     */
    public User updateUser(User user) {
        User u = userRepository.getOne(user.getId());
        copy(user, u);
        logService.saveLog("修改帐户","");
        return userRepository.save(u);
    }

    /**
     * 重置密码
     *
     * @param id 帐户 ID
     * @return 影响行数
     */
    public User resetPassword(Integer id) {
        User user = userRepository.getOne(id);
        Object obj = new SimpleHash("MD5", "111111", ByteSource.Util.bytes(user.getAccount()), 8);
        user.setPwd(obj.toString());
        logService.saveLog("重置密码","");
        return userRepository.save(user);
    }

    /**
     * 保存帐户及帐户拥有角色
     *
     * @param user    帐户信息
     * @param roleIds 角色 ID 数组
     * @return 影响行数
     */
    @Transactional(rollbackFor = Exception.class)
    public User saveUser(User user, Integer[] roleIds, Integer branchId) {
        Integer deptId = null;
        if (branchId != null) {
            deptId = deptMapper.findTopLevelDept(branchId);
        }
        Object obj = new SimpleHash("MD5", "111111", ByteSource.Util.bytes(user.getAccount()), 8);
        user.setPwd(obj.toString());
        user.setStatus(STATUS_NORMAL);
        user.setDeptId(deptId);
        user.setBranchId(branchId);
        user.setRecMsg(1);
        logService.saveLog("创建用户",user.getName());
        User u = userRepository.saveAndFlush(user);
        if (roleIds.length > 0) {
            userMapper.batchInsertUserRole(u.getId(), roleIds);
        }
        return u;
    }

    /**
     * 修改帐户及拥有角色
     *
     * @param user    帐户信息
     * @param roleIds 拥有角色ID
     * @return 影响行数
     */
    @Transactional(rollbackFor = Exception.class)
    public User updateUser(User user, Integer[] roleIds,Integer orgId, Integer deptId) {
        if(user.getTel().contains("NaN")){
            user.setTel("");
        }
        Integer dept = null;
        if (deptId != null) {
            dept = deptMapper.findTopLevelDept(deptId);
        }
        User u = userRepository.getOne(user.getId());
        u.setDeptId(deptId);
        u.setOrgId(orgId);
        u.setBranchId(dept);
        copy(user, u);
        u = userRepository.saveAndFlush(u);
        userMapper.deleteUserRoleByUserId(user.getId());
        if (roleIds!=null && roleIds.length>0) {
            userMapper.batchInsertUserRole(u.getId(), roleIds);
            logService.saveLog("修改用户",u.getName());
        }
        return u;
    }

    /**
     * 修改密码
     *
     * @param password 密码
     * @return 行数
     */
    public User updateUserPassword(String password) {
        User user = ShiroUtils.getUser();
        int hashIterations = 8;
        Object obj = new SimpleHash("MD5", password, ByteSource.Util.bytes(user.getAccount()), hashIterations);
        user.setPwd(obj.toString());
        logService.saveLog("修改密码",user.getName());
        return userRepository.save(user);
    }

    /**
     * 上传头像
     *
     * @param avatar 头像路径
     * @return user
     */
    public User updateAvatar(String avatar) {
        User user = ShiroUtils.getUser();
        user.setAvatar(avatar);
        user = userRepository.save(user);
        ShiroUtils.getSession().setAttribute("user", user);
        logService.saveLog("修改头像",user.getName());
        return user;
    }

    /**
     * 按ID查询用户
     *
     * @param id ID
     * @return User
     */
    public User findUserById(Integer id) {
        return userRepository.getOne(id);
    }

    public List<User> findUsers(User user) {
        return userMapper.findByConditionJoin(user);
    }
}
